Angular Router

URLs-ஐ views-க்கு map செய்து உங்கள் app-ல் users navigate செய்ய அனுமதிக்கிறது

Angular Router

Router URLs-ஐ views-க்கு map செய்து உங்கள் app-ல் users navigate செய்ய அனுமதிக்கிறது.

Router Essentials

  • URL-driven UI: Router URL-அடிப்படையில் views-ஐ swap செய்கிறது.
  • RouterOutlet: Active route-ன் component render செய்யும் placeholder.
  • routerLink: Full page reloads இல்லாமல் navigate செய்ய.
  • RouterLinkActive: Active links-க்கு classes add செய்கிறது (root-க்கு { exact: true } பயன்படுத்தவும்).
  • Performance & control: Feature areas lazy load செய்யவும்; navigation allow/block செய்ய guards பயன்படுத்தவும்.

Router Setup Example

import { provideRouter, withHashLocation, RouterOutlet, RouterLink } from '@angular/router';

const routes = [
  { path: '', component: Home },
  { path: 'about', component: About }
];

bootstrapApplication(App, {
  providers: [provideRouter(routes, withHashLocation())]
});

// Template
// <a routerLink="/about">About</a>
// <router-outlet></router-outlet>

Notes

  • Related: Components for building views, Services for shared logic/guards, and Templates for markup and directives ஆகியவற்றை காணவும்.
  • Standalone apps: RouterOutlet/RouterLink import செய்யவும் மற்றும் provideRouter() உடன் routes provide செய்யவும்.
  • Sandboxes/runners: Server config இல்லாமல் links work செய்ய withHashLocation() பயன்படுத்தவும் (hash URLs /#/path போல் தெரியும்).

Router Basics

Paths-ஐ components-க்கு map செய்ய routes array define செய்யவும்.

provideRouter() உடன் routes provide செய்யவும் (sandboxes-க்கு withHashLocation() பயன்படுத்தவும்).

Navigation-க்கு routerLink பயன்படுத்தவும் மற்றும் views render செய்ய RouterOutlet பயன்படுத்தவும்.

Basic Routes Syntax

const routes = [ { path: '', component: Home }, { path: 'about', component: About } ];
// template
// <a routerLink="/about">About</a>
// <router-outlet></router-outlet>

Example

Router Basics Example

import { bootstrapApplication } from '@angular/platform-browser';
import { Component } from '@angular/core';
import { provideRouter, RouterOutlet, RouterLink, withHashLocation } from '@angular/router';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, RouterLink],
  template: `
    <h3>Router</h3>
    <nav>
      <a routerLink="/">Home</a> |
      <a routerLink="/about">About</a>
    </nav>
    <router-outlet></router-outlet>
  `
})
export class App {}

@Component({
  standalone: true,
  template: `<p>Home works!</p>`
})
export class Home {}

@Component({
  standalone: true,
  template: `<p>About works!</p>`
})
export class About {}

const routes = [
  { path: '', component: Home },
  { path: 'about', component: About }
];

bootstrapApplication(App, {
  providers: [provideRouter(routes, withHashLocation())]
});

Example Explained

  • provideRouter(routes): App-க்கு routes register செய்கிறது.
  • RouterOutlet: Active route-ன் component render செய்யும் placeholder.
  • routerLink: Page reload இல்லாமல் navigate செய்கிறது.
  • withHashLocation(): Sandboxes-ல் server rewrites இல்லாமல் links work செய்ய hash URLs பயன்படுத்துகிறது.

Notes

  • Use routerLink, not href: href page reload செய்கிறது.
  • Use routerLink for SPA navigation.
  • Standalone imports: RouterOutlet/RouterLink import செய்யவும் மற்றும் provideRouter() உடன் routes provide செய்யவும்.

Router Params

Paths-ல் variables capture செய்ய :id உடன் (e.g., /product/42).

ActivatedRoute மூலம் அவற்றை read செய்யவும் (snapshot அல்லது paramMap observable).

Route with Parameter

{ path: 'product/:id', component: Product }
// class Product {
//  id = '';
//  route = inject(ActivatedRoute);
//  ngOnInit() { this.id = this.route.snapshot.paramMap.get('id') ?? ''; }
// }

Example

Router Params Example

import { bootstrapApplication } from '@angular/platform-browser';
import { Component, OnInit, inject } from '@angular/core';
import { provideRouter, RouterOutlet, RouterLink, RouterLinkActive, ActivatedRoute, withHashLocation } from '@angular/router';

@Component({
  selector: 'home-cmp',
  standalone: true,
  template: `<p>Home works!</p>`
})
export class Home {}

@Component({
  selector: 'product-cmp',
  standalone: true,
  template: `<p>Product ID: {{ id }}</p>`
})
export class Product implements OnInit {
  id = '';
  private route = inject(ActivatedRoute);
  ngOnInit() {
    this.id = this.route.snapshot.paramMap.get('id') ?? '';
  }
}

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, RouterLink, RouterLinkActive],
  template: `
    <h3>Router Params</h3>
    <nav>
      <a routerLink="/">Home</a> |
      <a routerLink="/product/1" routerLinkActive="active">Product 1</a> |
      <a routerLink="/product/2" routerLinkActive="active">Product 2</a>
    </nav>
    <router-outlet></router-outlet>
  `,
  styles: [`nav a { margin-right: 6px; } .active { font-weight: bold; }`]
})
export class App {}

const routes = [
  { path: '', component: Home },
  { path: 'product/:id', component: Product }
];

bootstrapApplication(App, {
  providers: [provideRouter(routes, withHashLocation())]
});

Example Explained

  • product/:id: id என்று named path parameter declare செய்கிறது.
  • ActivatedRoute: ngOnInit-ல் snapshot.paramMap.get('id') இலிருந்து id-ஐ read செய்கிறது.
  • Links: routerLink="/product/1" மற்றும் /product/2 parameterized navigation demonstrate செய்கின்றன.

Note

Params update within the same component: வெவ்வேறு params உடன் அதே route-க்கு navigate செய்யும் போது, one-time snapshot பயன்படுத்துவதற்கு பதிலாக paramMap (அல்லது params)-க்கு subscribe செய்யவும்.

Lazy-loaded Component

Navigation வரை code loading defer செய்ய loadComponent அல்லது loadChildren பயன்படுத்தவும்.

Bundles splitting செய்வதன் மூலம் initial load time improve செய்கிறது.

Lazy Loading Syntax

{ path: 'about', loadComponent: () => import('./about').then(m => m.About) }

Example

Lazy-loaded Component Example

import { bootstrapApplication } from '@angular/platform-browser';
import { Component } from '@angular/core';
import { provideRouter, RouterOutlet, RouterLink, withHashLocation } from '@angular/router';

@Component({
  standalone: true,
  template: `<p>Home works!</p>`
})
export class Home {}

@Component({
  standalone: true,
  template: `<p>About works (lazy)!</p>`
})
export class About {}

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, RouterLink],
  styles: [`
    nav a { margin-right: 8px; text-decoration: none; }
  `],
  template: `
    <h3>Lazy-loaded Component (loadComponent)</h3>
    <nav>
      <a routerLink="/">Home</a>
      <a routerLink="/about">About (lazy)</a>
    </nav>
    <router-outlet></router-outlet>
  `
})
export class App {}

const routes = [
  { path: '', component: Home },
  // Use Promise.resolve to simulate lazy loading without dynamic imports
  { path: 'about', loadComponent: () => Promise.resolve(About) }
];

bootstrapApplication(App, {
  providers: [provideRouter(routes, withHashLocation())]
});

Example Explained

  • loadComponent: Navigation வரை route-ன் component loading defer செய்கிறது (இங்கு Promise.resolve உடன் simulate செய்யப்பட்டது).
  • Routes: Home eager; About lazy.
  • Navigation: "About (lazy)" click செய்வது demand-ல் component load மற்றும் render செய்கிறது.

Notes

  • Route order and wildcards: Catch-all routes last வைக்கவும் அதனால் அவை மற்ற routes-ஐ swallow செய்யாது.
  • Deep-link refreshes: Server rewrites இல்லாமல், refreshes 404 ஆக முடியும்.
  • In demos/sandboxes use withHashLocation().

Route Guard (canActivate)

Guards navigation allowed என்பதை தீர்மானிக்கின்றன.

true (allow), false/UrlTree (block/redirect), அல்லது async equivalents return செய்யவும்.

Route Guard Syntax

export const authGuard = () => isLoggedIn ? true : inject(Router).createUrlTree(['/']);
{ path: 'protected', component: Protected, canActivate: [authGuard] }

Example

Route Guard Example

import { bootstrapApplication } from '@angular/platform-browser';
import { Component, inject } from '@angular/core';
import { provideRouter, RouterOutlet, RouterLink, withHashLocation, Router } from '@angular/router';

let loggedIn = false;

export const authGuard = () => {
  if (loggedIn) return true;
  const router = inject(Router);
  return router.createUrlTree(['/']);
};

@Component({
  standalone: true,
  template: `<p>Home (public).</p>
<p>Login to access protected route.</p>`
})
export class Home {}

@Component({
  standalone: true,
  template: `<p>Protected works! You are logged in.</p>`
})
export class Protected {}

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, RouterLink],
  styles: [`
    nav a { margin-right: 8px; text-decoration: none; }
    .status { margin-left: 8px; font-weight: 600; }
  `],
  template: `
    <h3>Route Guard (canActivate)</h3>
    <div class="toolbar">
      <button (click)="toggle()">{{ loggedIn ? 'Log out' : 'Log in' }}</button>
      <span class="status">Status: {{ loggedIn ? 'Logged in' : 'Logged out' }}</span>
    </div>
    <nav>
      <a routerLink="/">Home</a>
      <a routerLink="/protected">Protected</a>
    </nav>
    <router-outlet></router-outlet>
  `
})
export class App {
  get loggedIn() { return loggedIn; }
  toggle() { loggedIn = !loggedIn; }
}

const routes = [
  { path: '', component: Home },
  { path: 'protected', component: Protected, canActivate: [authGuard] }
];

bootstrapApplication(App, {
  providers: [provideRouter(routes, withHashLocation())]
});

Example Explained

  • authGuard: Logged in ஆக இருக்கும் போது true return செய்கிறது; இல்லையெனில் /-க்கு redirect செய்ய UrlTree return செய்கிறது.
  • inject(Router): Guard function-ல் redirect UrlTree create செய்ய Router-ஐ access செய்கிறது.
  • canActivate: /protected route-க்கு guard apply செய்கிறது.
  • Toggle: Button loggedIn state flip செய்கிறது இரண்டு branches test செய்ய.

Note

Guard return types: Boolean, UrlTree, அல்லது அவற்றின் observable/promise return செய்யவும்.

Exercise

Which directive updates the URL without reloading the page?

routerLink
✓ Correct! routerLink directive URL-ஐ page reload இல்லாமல் update செய்கிறது
href
✗ Incorrect! href attribute full page reload செய்கிறது
onclick
✗ Incorrect! onclick event handler மட்டுமே, router navigation-க்கு பயன்படாது
அடுத்தது